package com.cus.tom.transfer.frag;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.BuildConfig;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.trans.service.AppService;
import com.cus.tom.transfer.utils.ToastUtil;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class RecordAppFragment extends RecordImgFragment {

    LoadingDlg dlg = null;
    boolean first = true;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (Const.INSTALL_FINISH.equals(intent.getAction())) {
                ToastUtil.showShortToast(App.getApp(), "安装完成");
                if (dlg != null) {
                    dlg.dismiss();
                }
            }
        }
    };

    public RecordAppFragment(int type) {
        super(type);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        getActivity().registerReceiver(receiver, new IntentFilter(Const.INSTALL_FINISH));
        binding.export.setText("安装");
        binding.export.setOnClickListener(v -> {
            ArrayList<MediaData> list = adapter.getSelect();
            if (list.isEmpty()) {
                return;
            }
            installApp(list);
        });
        return view;
    }

    @Override
    protected List<MediaData> getMediaData() {
        if (!XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            return Collections.emptyList();
        }
        return dao.getAllByType(FileType.APP);
    }

    @Override
    protected boolean hasFile() {
        return type == 0 ? true : false;
    }

    ArrayList<MediaData> list;

    @Override
    public void installApp(ArrayList<MediaData> data) {
        if (!App.getApp().getPackageManager().canRequestPackageInstalls()) {
            TipDlg dlg = new TipDlg().setMsg("需要您授予安装应用权限");
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        list = data;
                        openInstallPermission(RecordAppFragment.this, 51);
                    }
                }
            });
            dlg.show(getChildFragmentManager(), "");
            return;
        }
        install(data);
    }

    private void install(ArrayList<MediaData> data) {
        if (data == null) {
            return;
        }
        PackageManager pm = getActivity().getPackageManager();
        Iterator<MediaData> it = data.iterator();
        while (it.hasNext()) {
            MediaData d = it.next();
            File f = new File(d.getPath());
            if (!f.exists()) {
                it.remove();
                continue;
            }
            PackageInfo pkgInfo = pm.getPackageArchiveInfo(d.getPath(), PackageManager.GET_ACTIVITIES);
            if (pkgInfo == null || pkgInfo != null && Utils.isInstalled(pkgInfo.packageName)) {
                it.remove();
            } else {
                d.pkg = pkgInfo.packageName;
            }
        }
        if (!data.isEmpty()) {
            dlg = new LoadingDlg().setMsg("正在安装应用");
            dlg.setCancelable(false);
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    dlg = null;
                }
            });
            dlg.show(getChildFragmentManager(), "");
            Intent intent = new Intent(getActivity(), AppService.class);
            intent.putExtra("from", 0);
            intent.putParcelableArrayListExtra("list", data);
            getActivity().startService(intent);
        }
    }

    private void openInstallPermission(Fragment fragment, int code) {
        Intent intent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
                    , Uri.parse("package:" + BuildConfig.APPLICATION_ID));
        } else {
            intent = new Intent(Settings.ACTION_SECURITY_SETTINGS
                    , Uri.parse("package:" + BuildConfig.APPLICATION_ID));
        }
        fragment.startActivityForResult(intent, code);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 51 && resultCode == Activity.RESULT_OK) {
            install(list);
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Intent i = new Intent(getActivity(), AppService.class);
            i.putExtra("from", 2);
            getActivity().startService(i);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (first) {
            return;
        }
        first = false;
        h.postDelayed(runnable, 2000);
    }

    @Override
    public void onPause() {
        super.onPause();
        h.removeCallbacks(runnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
